﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using UCNKompetenceBors.Database;
using UCNKompetenceBors.Model;

namespace UCNKompetenceBors.Admin
{
    public partial class adminNewsEdit : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                ckeditorEditNewsText.Width = 450;
                ckeditorEditNewsLocalizedText.Width = 450;
                this.Form.DefaultButton = btnAdminEditNews.UniqueID;

                BindSubMenu();
                BindData(Convert.ToInt32(Request.QueryString["nid"]));

                lblConfirmUpdatedNews.Visible = false;

                #region Globalization
                string culture = String.Empty;

                if (HttpContext.Current.Session["MyCulture"] != null)
                    culture = HttpContext.Current.Session["MyCulture"].ToString();

                if (!String.IsNullOrEmpty(culture))
                    GeneralTools.SetCulture(culture);

                LocalizeControls();
                #endregion
            }
        }

        /// <summary>
        /// Binds the sub menu links.
        /// </summary>
        private void BindSubMenu()
        {
            hyLinkAdminDashboard.NavigateUrl = "~/Admin/admin.aspx";
            hyLinkUserHandling.NavigateUrl = "~/Admin/adminUsers.aspx";
            hyLinkAdminExchange.NavigateUrl = "~/Admin/adminExchange.aspx";
            hyLinkNewsHandling.NavigateUrl = "~/Admin/adminNews.aspx";
            hyLinkEditInformation.NavigateUrl = "~/Admin/adminInformation.aspx";
            hyLinkResetUsers.NavigateUrl = "~/Admin/adminUsersReset.aspx";
            hyLinkContactPerson.NavigateUrl = "~/Admin/adminContactPerson.aspx";
            hylinkDepartment.NavigateUrl = "~/Admin/adminDepartment.aspx";
            hyLinkAdminCreateNews.NavigateUrl = "~/Admin/adminNewsCreate.aspx";
        }

        /// <summary>
        /// Binds the controls with a news article, based on the newsId parameter.
        /// </summary>
        /// <param name="newsId">Specifies the ID of the news article to be used.</param>
        private void BindData(int newsId)
        {
            News news = dbAdmin.GetNewsById(newsId);

            lblCreatedDate.Text = news.CreatedDate.ToString("dd-MM-yyyy");
            txtEditNewsTitle.Text = news.Title;
            ckeditorEditNewsText.Text = news.Text;
            txtEditNewsLocalizedTitle.Text = news.LocalizedTitle;
            ckeditorEditNewsLocalizedText.Text = news.LocalizedText;
            imgEditNewsImage.ImageUrl = news.ImageURL;
        }

        /// <summary>
        /// Edits a news article, based on the newsId parameter.
        /// </summary>
        /// <param name="title">Specifies the title to be used.</param>
        /// <param name="text">Specifies the text to be used.</param>
        /// <param name="hasImage">Specifies whether or not news article has an image.</param>
        /// <param name="imagePath">Specifies the path of the current image.</param>
        /// <param name="imageFileName">Specifies the file name of the image to be used.</param>
        /// <param name="newsId">Specifies the ID of the news article to be used.</param>
        /// <param name="locTitle">Specifies the title to be used in the localized news article.</param>
        /// <param name="locText">Specifies the text to be used in the localized news article.</param>
        private void EditNews(string title, string text, bool hasImage, string imageFileName, int newsId, string locTitle, string locText)
        {
            string path = "";
            
            //Checks whether or not an image has been selected in the fileupload control
            if (hasImage)
            {
                //Checks whether or not current image is the default image
                if (!imgEditNewsImage.ImageUrl.Equals("~/Images/News/default.jpg"))
                {
                    //If the current image is not the default image, the old image is deleted
                    DeleteImage(Convert.ToInt32(Request.QueryString["nid"]), imgEditNewsImage.ImageUrl);
                    path = Path.GetDirectoryName(imgEditNewsImage.ImageUrl);
                }
                else
                {
                    path = Path.GetDirectoryName("~/Images/News/" + txtEditNewsTitle.Text.Trim() + "_" + lblCreatedDate.Text + "/");
                }                
                
                UploadPicture();
            }

            dbAdmin.EditNews(title, text, hasImage, path, imageFileName, newsId, locTitle, locText);


        }

        /// <summary>
        /// Upload an image.
        /// </summary>
        private void UploadPicture()
        {
            string filePath = String.Empty;
            string dirPath = String.Empty;

            //Checks whether or not current image is the default image 
            if (!imgEditNewsImage.ImageUrl.Equals("~/Images/News/default.jpg"))
            {
                //If the current image is not the default image, filepath is set to the MapPath to the current imageURL
                filePath = Path.GetDirectoryName(imgEditNewsImage.ImageUrl) + "\\";
                dirPath = Server.MapPath(filePath);
            }
            else
            {
                //If the current image is the default image, the new filepath is set to the title + the created date
                filePath = "~/Images/News/" + txtEditNewsTitle.Text.Trim() + "_" + lblCreatedDate.Text + "/";
                dirPath = Server.MapPath(filePath);
            }
            
            //Checks whether or not the directory exists
            if (Directory.Exists(dirPath))
            {
                if (fuEditNewsImage.HasFile)
                    fuEditNewsImage.SaveAs(dirPath + fuEditNewsImage.FileName);
            }
            else
            {
                DirectoryInfo dir = new DirectoryInfo(dirPath);

                dir.Create();

                if (fuEditNewsImage.HasFile)
                    fuEditNewsImage.SaveAs(dirPath + fuEditNewsImage.FileName);
            }
        }

        /// <summary>
        /// Checks whether or not a news article has an image, based on the newsId parameter.
        /// </summary>
        /// <param name="newsId">Specifies the ID of the news article to be used.</param>
        /// <returns>Returns a boolean, specifying whether or not a news article has an image.</returns>
        private bool HasImage(int newsId)
        {
            return dbAdmin.NewsHasImage(newsId);
        }

        /// <summary>
        /// Deletes an image, based on the newsId and imagePath parameters.
        /// </summary>
        /// <param name="newsId">Specifies the ID of the news article to be used.</param>
        /// <param name="imagePath">Specifies the path of the image to be deleted</param>
        private void DeleteImage(int newsId, string imagePath)
        {
            if (HasImage(newsId))
            {
                string filePath = HttpContext.Current.Server.MapPath(imagePath);

                //Removes the filename from the path
                string path = Path.GetDirectoryName(filePath);

                File.Delete(filePath);
            }
        }

        protected void btnAdminEditNews_Click(object sender, EventArgs e)
        {
            if (Page.IsValid)
            {
                lblConfirmUpdatedNews.Visible = true;
                string title = txtEditNewsTitle.Text;
                string text = ckeditorEditNewsText.Text;
                bool hasImage = fuEditNewsImage.HasFile;
                string imageFileName = fuEditNewsImage.FileName;
                string locTitle = txtEditNewsLocalizedTitle.Text;
                string locText = ckeditorEditNewsLocalizedText.Text;
                int newsId = Convert.ToInt32(Request.QueryString["nid"]);

                EditNews(title, text, hasImage, imageFileName, newsId, locTitle, locText);
            }            
        }

        /// <summary>
        /// Localizes the controls of the site, based on the current UI Culture.
        /// </summary>
        private void LocalizeControls()
        {
            hyLinkAdminDashboard.Text = GetLocalResourceObject("hyLinkAdminDashboardText").ToString();
            hyLinkUserHandling.Text = GetLocalResourceObject("hyLinkUserHandlingText").ToString();
            hyLinkAdminExchange.Text = GetLocalResourceObject("hyLinkAdminExchangeText").ToString();
            hyLinkNewsHandling.Text = GetLocalResourceObject("hyLinkNewsHandlingText").ToString();
            hyLinkEditInformation.Text = GetLocalResourceObject("hyLinkEditInformationText").ToString();
            hyLinkResetUsers.Text = GetLocalResourceObject("hyLinkResetUsersText").ToString();
            hyLinkContactPerson.Text = GetLocalResourceObject("hyLinkContactPersonText").ToString();
            hylinkDepartment.Text = GetLocalResourceObject("hylinkDepartmentText").ToString();
            hyLinkAdminCreateNews.Text = GetLocalResourceObject("hyLinkAdminCreateNewsText").ToString();

            lblAdminContentHeader.Text = GetLocalResourceObject("lblAdminContentHeaderText").ToString();
            lblEditNewsImage.Text = GetLocalResourceObject("lblEditNewsImageText").ToString();
            lblEditNewsText.Text = GetLocalResourceObject("lblEditNewsTextText").ToString();
            lblEditNewsTitle.Text = GetLocalResourceObject("lblEditNewsTitleText").ToString();
            lblEditNewsLocalizedTitle.Text = GetLocalResourceObject("lblEditNewsLocalizedTitleText").ToString();
            lblEditNewsLocalizedText.Text = GetLocalResourceObject("lblEditNewsLocalizedTextText").ToString();
            lblConfirmUpdatedNews.Text = GetLocalResourceObject("lblConfirmUpdatedNewsText").ToString();
            lblLocalized.Text = GetLocalResourceObject("lblLocalizedText").ToString();

            btnAdminEditNews.Text = GetLocalResourceObject("btnAdminEditNewsText").ToString();

            btnCancelEditNews.Text = GetLocalResourceObject("btnCancelEditNewsText").ToString();

            string imageValidaton = GetLocalResourceObject("regexvalEditNewsImageText").ToString();
            regexvalEditNewsImage.ToolTip = imageValidaton;
            regexvalEditNewsImage.ErrorMessage = imageValidaton;

            string textValidation = GetLocalResourceObject("rfvalTextText").ToString();
            rfvalText.ToolTip = textValidation;
            rfvalText.ErrorMessage = textValidation;

            string titleValidation = GetLocalResourceObject("rfvalTitleText").ToString();
            rfvalTitle.ToolTip = titleValidation;
            rfvalTitle.ErrorMessage = titleValidation;

            string englishTitleValidation = GetLocalResourceObject("rfvalEditNewsLocalizedTitleText").ToString();
            rfvalEditNewsLocalizedTitle.ToolTip = englishTitleValidation;
            rfvalEditNewsLocalizedTitle.ErrorMessage = englishTitleValidation;

            string englishTextValidation = GetLocalResourceObject("rfvalEditNewsLocalizedTextText").ToString();
            rfvalEditNewsLocalizedText.ToolTip = englishTextValidation;
            rfvalEditNewsLocalizedText.ErrorMessage = englishTextValidation;

            valSumAdminEditNews.HeaderText = GetLocalResourceObject("valSumAdminEditNewsText").ToString();

            string culture = String.Empty;

            if (HttpContext.Current.Session["MyCulture"] != null)
                culture = HttpContext.Current.Session["MyCulture"].ToString();

            if (culture.Equals("en-GB"))
            {
                ckeditorEditNewsLocalizedText.Language = "en";
                ckeditorEditNewsText.Language = "en";
            }
            else
            {
                ckeditorEditNewsLocalizedText.Language = "da";
                ckeditorEditNewsText.Language = "da";
            }
        }

        protected void btnCancelEditNews_Click(object sender, EventArgs e)
        {
            Response.Redirect("~/Admin/adminNews.aspx");
        }
    }
}